package boot.spring.task;

import boot.spring.service.TouristService;
import boot.spring.util.HttpUtils;
import boot.spring.vo.TourisExportVo;
import boot.spring.vo.TouristImportVo;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.redisson.api.RBucket;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.util.*;

import java.io.IOException;

@Component
@EnableScheduling
public class MyCronTask {

    private static final Logger logger = LoggerFactory.getLogger(MyCronTask.class);

    @Resource
    RedissonClient redissonClient;

    @Resource
    TouristService touristService;

    @Value("${tour.token}")
    private String token;

    @Value("${tour.day}")
    private Integer day;

    @Scheduled(fixedDelay = 600 * 1000)
    void cronSchedule(){
        String url = "https://tyfx.dpm.org.cn//zybuser/user/userMsg";
        JSONObject result = this.doGetAuthorization(url);
        logger.info("cron schedule execute ["+ result.toJSONString() +"]");
    }

    @Scheduled(cron = "0 00 20 * * ? ")
//    @Scheduled(fixedDelay = 5000 * 1000)
    void fixedRateSchedule() throws InterruptedException, ParseException {
        touristService.initRedis();
        boolean keyExists = redissonClient.getBucket("TOUR_KEY").isExists();
        boolean isSuccessOne = false;
        boolean isSuccessTwo = false;
        while (keyExists) {
            try{
                RMap<String, Object> map = redissonClient.getMap("TOUR_KEY");
                RBucket<String> stringdata = redissonClient.getBucket("PRIORITY_KEY");
                RBucket<String> guide = redissonClient.getBucket("GUIDE_KEY");
                String priority = stringdata.get();
                List<TouristImportVo> lnList = (List<TouristImportVo>) map.get("ln");
                List<TouristImportVo> xsList = (List<TouristImportVo>) map.get("xs");
                List<TouristImportVo> crList = (List<TouristImportVo>) map.get("cr");
                List<TouristImportVo> wcnList = (List<TouristImportVo>) map.get("wcn");
                List<TourisExportVo> noList = new ArrayList<>();
                // 到九点自动删除redis 跳出循环
                LocalTime currentTime = LocalTime.now();
                LocalTime nineAm = LocalTime.of(21, 0);
                if (currentTime.isAfter(nineAm)) {
                    if(map.containsKey("ln")) {
                        for (TouristImportVo touristImportVo : lnList) {
                            TourisExportVo exportVo = new TourisExportVo();
                            BeanUtils.copyProperties(touristImportVo, exportVo);
                            noList.add(exportVo);
                        }
                    }
                    if(map.containsKey("xs")) {
                        for (TouristImportVo touristImportVo : xsList) {
                            TourisExportVo exportVo = new TourisExportVo();
                            BeanUtils.copyProperties(touristImportVo, exportVo);
                            noList.add(exportVo);
                        }
                    }
                    if(map.containsKey("cr")) {
                        for (TouristImportVo touristImportVo : crList) {
                            TourisExportVo exportVo = new TourisExportVo();
                            BeanUtils.copyProperties(touristImportVo, exportVo);
                            noList.add(exportVo);
                        }
                    }
                    if(map.containsKey("wcn")) {
                        for (TouristImportVo touristImportVo : wcnList) {
                            TourisExportVo exportVo = new TourisExportVo();
                            BeanUtils.copyProperties(touristImportVo, exportVo);
                            noList.add(exportVo);
                        }
                    }

                    // 导出未处理的数据
                    try{
                        EasyExcel.write("未抢到票的数据.xls", TourisExportVo.class)
                                .autoCloseStream(false)
                                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet").doWrite(noList);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    map.delete();stringdata.delete();guide.delete();
                    break;
                }


                List<Map<String,Object>> allOrder = new ArrayList<>();
                Map<String,List<TouristImportVo>> dataMap = new HashMap<>();
                // 获取查询的库存日期
                String dayStr = getSDay(day);
                if(CollUtil.isNotEmpty(lnList)){
                    Map<String,Object> ticketMap = new HashMap<>();
                    ticketMap.put("ticketCode","TYMP20220704005223");
                    ticketMap.put("stockCode","SC220726150744994");
                    ticketMap.put("amount",lnList.size() + "");
                    if (priority.equals("上午")){
                        ticketMap.put("startTime","06-00");
                    }else{
                        ticketMap.put("startTime","11-00");
                    }
                    allOrder.add(ticketMap);
                    dataMap.put("老年人票",lnList);
                }

                if(CollUtil.isNotEmpty(xsList)){
                    Map<String,Object> ticketMap = new HashMap<>();
                    ticketMap.put("ticketCode","TYMP20220704005225");
                    ticketMap.put("stockCode","SC220726150744994");
                    ticketMap.put("amount",xsList.size() + "");
                    if (priority.equals("上午")){
                        ticketMap.put("startTime","06-00");
                    }else{
                        ticketMap.put("startTime","11-00");
                    }
                    allOrder.add(ticketMap);
                    dataMap.put("学生票",xsList);
                }

                if(CollUtil.isNotEmpty(crList)){
                    Map<String,Object> ticketMap = new HashMap<>();
                    ticketMap.put("ticketCode","TYMP20220704005220");
                    ticketMap.put("stockCode","SC220726150744994");
                    ticketMap.put("amount",crList.size() + "");
                    if (priority.equals("上午")){
                        ticketMap.put("startTime","06-00");
                    }else{
                        ticketMap.put("startTime","11-00");
                    }
                    allOrder.add(ticketMap);
                    dataMap.put("成人团队票",crList);
                }

                if(CollUtil.isNotEmpty(wcnList)){
                    Map<String,Object> ticketMap = new HashMap<>();
                    ticketMap.put("ticketCode","TYMP20220709005358");
                    ticketMap.put("stockCode","SC220709115524471");
                    ticketMap.put("amount",wcnList.size() + "");
                    if (priority.equals("上午")){
                        ticketMap.put("startTime","06-00");
                    }else{
                        ticketMap.put("startTime","11-00");
                    }
                    allOrder.add(ticketMap);
                    dataMap.put("团队未成年人免费票",wcnList);
                }


                // 提交第一步订单
                if(CollUtil.isNotEmpty(allOrder)){
                    Map<String,Long> ticketMap = touristService.submitOrderOne(allOrder, dayStr);
                    if(Objects.isNull(ticketMap)){
                        map.remove("ln");
                        map.remove("xs");
                        map.remove("cr");
                        map.remove("wcn");
                        stringdata.delete();guide.delete();
                        break;
                    }
                    isSuccessOne = true;
//                    Thread.sleep(20 * 1000);
                    isSuccessTwo = touristService.submitOrderTwo(dataMap,priority,guide.get(),ticketMap,dayStr);
                    if(isSuccessTwo){
                        map.remove("ln");
                        map.remove("xs");
                        map.remove("cr");
                        map.remove("wcn");
                        stringdata.delete();guide.delete();
                        break;
                    }
                }



                // 所有游客预定完成 删除redis 跳出循环
                RMap<String, Object> mapNew = redissonClient.getMap("TOUR_KEY");
                if(!mapNew.containsKey("ln")
                        && !mapNew.containsKey("xs")
                        && !mapNew.containsKey("cr")
                        && !mapNew.containsKey("wcn")
                ){
                    mapNew.delete();
                    RBucket<String> newStr = redissonClient.getBucket("PRIORITY_KEY");
                    newStr.delete();
                    RBucket<String> guideKey = redissonClient.getBucket("GUIDE_KEY");
                    guideKey.delete();
                    break;
                }
                // 防止接口被拦截，每俩分钟执行一批
//                Thread.sleep(120000);
            } catch (Exception e) {
                isSuccessOne = false;
                isSuccessTwo = false;
                break;
            }
        }
        List<TourisExportVo> noList = new ArrayList<>();
        RMap<String, Object> map = redissonClient.getMap("TOUR_KEY");
        RBucket<String> stringdata = redissonClient.getBucket("PRIORITY_KEY");
        RBucket<String> guide = redissonClient.getBucket("GUIDE_KEY");
        if(!isSuccessOne || !isSuccessTwo){
            if(map.containsKey("ln")) {
                List<TouristImportVo> list1 = (List<TouristImportVo>) map.get("ln");
                for (TouristImportVo touristImportVo : list1) {
                    TourisExportVo exportVo = new TourisExportVo();
                    BeanUtils.copyProperties(touristImportVo, exportVo);
                    noList.add(exportVo);
                }
            }
            if(map.containsKey("xs")) {
                List<TouristImportVo> list2 = (List<TouristImportVo>) map.get("xs");
                for (TouristImportVo touristImportVo : list2) {
                    TourisExportVo exportVo = new TourisExportVo();
                    BeanUtils.copyProperties(touristImportVo, exportVo);
                    noList.add(exportVo);
                }
            }
            if(map.containsKey("cr")) {
                List<TouristImportVo> list3 = (List<TouristImportVo>) map.get("cr");
                for (TouristImportVo touristImportVo : list3) {
                    TourisExportVo exportVo = new TourisExportVo();
                    BeanUtils.copyProperties(touristImportVo, exportVo);
                    noList.add(exportVo);
                }
            }
            if(map.containsKey("wcn")) {
                List<TouristImportVo> list4 = (List<TouristImportVo>) map.get("wcn");
                for (TouristImportVo touristImportVo : list4) {
                    TourisExportVo exportVo = new TourisExportVo();
                    BeanUtils.copyProperties(touristImportVo, exportVo);
                    noList.add(exportVo);
                }
            }

            // 导出未处理的数据
            try{
                EasyExcel.write("未抢到票的数据.xls", TourisExportVo.class)
                        .autoCloseStream(false)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("sheet").doWrite(noList);
            }catch (Exception e){
                e.printStackTrace();
            }
            map.delete();stringdata.delete();guide.delete();

        }
    }


    public static String getSDay(int day){
        // 获取当前日期时间
        Date currentDate = new Date();

        // 创建 Calendar 对象，并设置为当前日期时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);

        calendar.add(Calendar.DAY_OF_YEAR, day);

        // 得到增加七天后的日期时间
        Date futureDate = calendar.getTime();

        // 将日期时间转换为字符串
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String futureDateStr = format.format(futureDate);

        return futureDateStr;
    }




    public static void main(String[] args) throws IOException {

        long cu = System.currentTimeMillis();
        String data = "[{\"goodsCode\":\"TYMP20220704005223\",\"ticketId\":1036,\"quantity\":1,\"occDate\":\"2024-09-14\",\"isGiftTicket\":\"F\",\"occStartTime\":\"11:00\",\"occEndTime\":\"17:00\",\"customerInfos\":[{\"authType\":\"IC\",\"certNo\":\"140122199405301115\",\"realName\":\"董鑫\"}]},{\"goodsCode\":\"TYMP20220704005220\",\"ticketId\":1035,\"quantity\":1,\"occDate\":\"2024-09-14\",\"isGiftTicket\":\"F\",\"occStartTime\":\"11:00\",\"occEndTime\":\"17:00\",\"customerInfos\":[{\"authType\":\"IC\",\"certNo\":\"140122199402111121\",\"realName\":\"赵素萍\"}]}]";
        JSONArray d = JSON.parseArray(data);
        String json = "{\"totalPrice\":\"9000\",\"goodsList\":"+d+",\"contactPerson\":{\"linkName\":\"王慧\",\"linkTel\":\"13633243055\",\"certNo\":\"130803198007280200\",\"authType\":\"IC\"},\"saveOrderFlag\":\"F\",\"scenicId\":242,\"scenicName\":\"故宫博物院\",\"timesTamp\":1725844514813,\"sign\":\"fe995ab94f1810e5f39a46158d1a8c6c6b1466c743c494d0d3445d8e2ee28c492b124b6251c52c406d51113d6db0ca53\"}";
        JSONObject j = JSON.parseObject(json);
        j.put("sign",encryptOrder(d,cu));
        j.put("timesTamp",cu);

        Connection.Response response = Jsoup.connect("https://lotsmg.dpm.org.cn/tyApi/zyborder/order/saveUnpaidOrder")
                .header("Accept", "application/json, text/plain, */*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json;charset=UTF-8")
                .cookie("SESSIONID", "cc229d5a-4771-4852-afa2-7d5dea992d51")
                .cookie("curUrl", "")
                .cookie("SESSION", "YWQxNzk5YzAtNWE3ZC00M2Y1LTk4YTAtZmQwMWZiZjMxMzEz")
                .cookie("SameSite", "None")
                .cookie("pub_corp_code", "GGBWY")
                .cookie("apply-subject-id", "7750021414424576")
                .cookie("activeName", "tongye")
                .cookie("acw_tc", "b65cfd2a17258443397206291e4ff52c8d2572e854a0da27c9ea36a6667edd")
                .cookie("ssxmod_itna", "iq+x0DuDcQ3xBGDzame0")
                .cookie("ssxmod_itna2", "iq+x0DuDcQ3xBGDzame0")
                .cookie("tfstk", "fWgoqxaKI0r598j0inzWvGo5V0xxg_aI8vQLpyee0-ybJ8eLe2X3nAyL2Xz8Y92mdkerw3i3-AkgUwU-99YEB-gKw8eLYeDnswh8yX3mKXDZ2WUzykPnBXH3AQwLLJDKT0dvWFhSNyaUKdL9WWOW9kk3aarF3BPLt7ophhCSNyaeHHKsSJGSIiUI8B4eirPL6WzUY8z2i5Pg8arFziy4h-yU8gPz3-PQ6a7F8vl2iWw4TbL18R0ElqJPov20QbIgm7quKwHV-mihWyeN3-_dJ8qbqghznw7Eomsut0eyfseQy8GzZvT1PzrnY4UqzK8U7cMm-lzMvQZrtmDQyqRF4Ro-ekg7mTSzsz2ub4rl6ZhbYm00y4JCfjh0Ul4xDn98vzDofRZycKMni8HEroWkHJntM4rmQKQmdkmEyruy3FjzxiSwSP7IhpmfAMZzGS2TuWs8kydPtcODiGt74SNJBIAcAMZzGS29iIj1duPbwdC..")
                .header("Origin", "https://lotsmg.dpm.org.cn")
                .header("Referer", "https://lotsmg.dpm.org.cn/manage/tongye/distribution-order/orderform?ticketListVOS=ticketCode%3ATYMP20220704005223%7Camount%3A1%7CstartTime%3A11-00%7CstockCode%3ASC220726150744994,ticketCode%3ATYMP20220704005220%7Camount%3A1%7CstartTime%3A11-00%7CstockCode%3ASC220726150744994&ownerCorpCode&scenicName=%E6%95%85%E5%AE%AB%E5%8D%9A%E7%89%A9%E9%99%A2&scenicId=242")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
                .header("device-token", "v2:wqkBPAQhvDKa02qP3hO2Aw/Vq7tmKqTtdteQFncIMm8ey1GIkwgcsiL7XyMgqg501oRmKs/WbttbOugtlqPemFxyX127G6e3PvMmmL3/RltiuDgljfF0ITlcvB3IH+7uLzecdf308FaGVMZI59QK93MPsIPoMYYqu3gjs64AtoOAptqkLa3JsJOg6O4UWy5l9YdFbZ+Ujz2qBEzd7plCE7HDajQ3Vu0x6cw0jAjGIstmcBJgyhTm9luG3+IBThC/jr72")
                .header("sec-ch-ua", "\"Not=A?Brand\";v=\"99\", \"Chromium\";v=\"118\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .header("tyAuthToken", "21A3FC8EA97D48158F0F22D839189DA1")
                .requestBody(j.toJSONString())
                .method(org.jsoup.Connection.Method.POST)
                .ignoreContentType(true)
                .execute();

        System.out.println(response.parse());
    }

    private static String encryptOrder(JSONArray str, long time) throws IOException {
        String params = "group=test_web&action=getEncryptSign&l="+str+"&m="+time+"&bind_client=0.192903304593127";
        URL url = new URL("http://127.0.0.1:5612/business-demo/invoke");
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
        writer.write(params);
        writer.flush();
        writer.close();
        httpConn.getOutputStream().close();
        InputStream responseStream = httpConn.getResponseCode() / 100 == 2
                ? httpConn.getInputStream()
                : httpConn.getErrorStream();
        Scanner s = new Scanner(responseStream).useDelimiter("\\A");
        String response = s.hasNext() ? s.next() : "";
        System.out.println(response);
        JSONObject json = JSON.parseObject(response);
        return json.getString("data");
    }

    public JSONObject doGetAuthorization(String url) {
        Map<String, String> headers=new HashMap<>();
        headers.put("Tyauthtoken", token);
        String xx=HttpUtils.Get(url, headers);
        return JSONObject.parseObject(xx);
    }

}
